using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseWrite.API.Applications.Commands.Drugstores;
using MediatR;

namespace ContentmanagementBaseWrite.API.Applications.Commandhandlters.Drugstores
{
    /// <summary>
    /// 新增药店命令处理
    /// </summary>
    public class AddNewDrugstoreCommandHandler : IRequestHandler<AddNewDrugstoreCommand, ApiResult<int>>
    {
        /// <summary>
        /// 药店仓储
        /// </summary>
        private readonly IBaseRepository<PharmacyManagementModel> _drugstoreRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<AddNewDrugstoreCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="drugstoreRepository">药店仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public AddNewDrugstoreCommandHandler(IBaseRepository<PharmacyManagementModel> drugstoreRepository, IMapper mapper, ILogger<AddNewDrugstoreCommandHandler> logger)
        {
            _drugstoreRepository = drugstoreRepository;
            this.mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理新增药店命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddNewDrugstoreCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证药店名称是否已存在
                var existingDrugstores = _drugstoreRepository.GetAll().Where(x => x.PharmacyName == request.PharmacyName);
                // 如果已存在，返回错误
                if (existingDrugstores.Any())
                {
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.error,
                        message = "药店名称已存在！",
                        data = 0
                    };
                }

                _logger.LogInformation("开始处理药店新增命令，药店名称：{PharmacyName}", request.PharmacyName);

                // 创建药店实体
                var drugstoreEntity = mapper.Map<PharmacyManagementModel>(request);
                drugstoreEntity.CreatedTime = DateTime.Now;
                drugstoreEntity.UpdatedTime = DateTime.Now;
                drugstoreEntity.CreatedBy = 1;
                drugstoreEntity.UpdatedBy = 0;

                _logger.LogDebug("药店实体映射完成，实体信息：{@Entity}", drugstoreEntity);

                // 保存到数据库
                _logger.LogInformation("开始保存药店到数据库");
                var result = await _drugstoreRepository.AddAsync(drugstoreEntity);
                _logger.LogInformation("数据库保存完成，影响行数：{Result}", result);

                if (result > 0)
                {
                    _logger.LogInformation("药店新增成功，ID：{Id}", drugstoreEntity.Id);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.Ok,
                        message = "药店新增成功",
                        data = drugstoreEntity.Id
                    };
                }
                else
                {
                    _logger.LogWarning("药店新增失败，数据库未返回影响行数");
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.fails,
                        message = "药店新增失败",
                        data = 0
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "药店新增过程中发生异常，药店名称：{PharmacyName}", request.PharmacyName);
                return new ApiResult<int>
                {
                    code = ResultEnumCode.fails,
                    message = $"药店新增异常：{ex.Message}",
                    data = 0
                };
            }
        }
    }
}